package com.my.socket.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.List;

/**
 * Created by ZhongGang
 * at 2017/6/29 10:22
 */
public class StringCodec extends ByteToMessageCodec<String> {
    private static final Logger LOGGER = LoggerFactory.getLogger(StringCodec.class);

    private String charset = "UTF-8";

    public StringCodec() {
        this("UTF-8");
    }

    public StringCodec(String charset) {
        if (charset == null) {
            throw new NullPointerException();
        }
        this.charset = charset;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
        LOGGER.info("encode message: {}, reader index: {}, writer index: {}, capacity: {}", msg, out.readerIndex(), out.writerIndex(), out.capacity());
        out.writeCharSequence(msg, Charset.forName(this.charset));
        LOGGER.info("encode message: {}, reader index: {}, writer index: {}, capacity: {} in channel {}", msg, out.readerIndex(), out.writerIndex(), out.capacity(), ctx.channel());
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        LOGGER.info("decode - reader index: {}, writer index: {}, capacity: {}", in.readerIndex(), in.writerIndex(), in.capacity());
        String message = (String) in.readCharSequence(in.readableBytes(), Charset.forName(this.charset));
        LOGGER.info("decode message: {} - reader index: {}, writer index: {}, capacity: {} in channel {}", message, in.readerIndex(), in.writerIndex(), in.capacity(), ctx.channel());
        out.add(message);
    }
}
